<?php

class OrderController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model_id = $this->loadModel($id);
		$oderDetail = OrderDetail::model()->findAll("order_id='".$id."'");
		$str = '<div class="CSSTableGenerator" >
                <table >
                    <tr>
                        <td>
                            STT
                        </td>
                        <td >
                            Sản phẩm
                        </td>
                        <td>
                            Giá đơn vị
                        </td>
						<td>
                            Số lượng
                        </td>
						<td>
                            Thành tiền
                        </td>
						<td>
                            Phí vận chuyển
                        </td>
						<td>
                            Tổng cộng
                        </td>
                    </tr>';
		$i = 1;$sl = 0; $thanh_tien = 0; $phi = 0;$total = 0;
		foreach($oderDetail as $item ){
			$product = Product::model()->findAll("id='".$item->product_id."'");
						$str .= "<tr>
							<td>".$i++."</td>
							<td>".CHtml::link(CHtml::encode($product[0]->name),array('admin/productadmin/view', 'id'=>$product[0]->id),array('target' => '_blank'))."</td>
							<td>".number_format($product[0]->on_sale,0)."</td>
							<td>".$item->quantity."</td>
							<td>".number_format($item->price,0)."</td>
							<td>".number_format($item->shipping_cost,0)."</td>
							<td>".number_format($item->price + $item->shipping_cost,0)."</td>";
			$sl += $item->quantity; $thanh_tien += $item->price; $phi = $item->shipping_cost;$total += ($item->price + $item->shipping_cost);
			$str .="</tr>";
		}
		$str .= "<tr>
							<td colspan='3'>Tổng cộng</td>
							<td>". number_format($sl,0)."</td>
							<td>". number_format($thanh_tien,0)." VNĐ</td>
							<td>". number_format($phi,0)." VNĐ</td>
							<td>". number_format($total,0)." VNĐ</td>
						</tr>
                </table>
		</div>";
		
        $model_id->scenario = 'admin';
		$this->render('view',array(
			'model'=>$model_id,'str' => $str,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	// public function actionCreate()
	// {
		// $model=new Order;
        // $model->scenario = 'admin';
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		// if(isset($_POST['Order']))
		// {
			// $model->attributes=$_POST['Order'];
			// if($model->save())
				// $this->redirect(array('view','id'=>$model->id));
		// }

		// $this->render('create',array(
			// 'model'=>$model,
		// ));
	// }

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
        $model->scenario = 'admin';
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Order']))
		{
			$tmp = $_POST['Order'];
			$model->attributes=$tmp;
			if($model->save()){
				if ( $tmp['status'] != 0 ){
					$oderDetail = OrderDetail::model()->findAll("order_id='".$id."'");
					// print_r($oderDetail);die;
					$tr = '';
					$i = 1;
					$sl = 0;
					$thanh_tien = 0;
					foreach ($oderDetail as $item) {
							$product = Product::model()->findAll("id='".$item->product_id."'");
							$total = $product[0]->on_sale*$item->quantity;
							$sl += $item->quantity;
							$thanh_tien += $total;
							$tr .= "<tr>
										<td style='border:1px solid black;'>".$i++."</td>
										<td style='border:1px solid black;'>".$product[0]->name."</td>
										<td style='border:1px solid black;'>".number_format($product[0]->on_sale,0)."</td>
										<td style='border:1px solid black;'>".$item->quantity."</td>
										<td style='border:1px solid black;'>".number_format($total,0)."</td>
									</tr>";
						
					}
					$str = "Chào bạn,<br><br>Trạng thái đơn hàng của bạn:".( $tmp['status'] == 1 ? '<b>THÀNH CÔNG</b>' : '<b>THẤT BẠI</b>')."<br><br>";
					$str .= "<table style='border-collapse:collapse;'><tr style='border:1px solid black;'><td style='border:1px solid black;'>STT</td><td style='border:1px solid black;'>Sản phẩm</td><td style='border:1px solid black;'>Giá đơn vị</td><td style='border:1px solid black;'>Số lượng</td><td style='border:1px solid black;'>Thành tiền</td></tr>";
					$str .= $tr;
					$str .= "<tr style='border:1px solid black;'>
						<td colspan='3'style='border:1px solid black;'>Tổng cộng:</td>
						<td style='border:1px solid black;'>".number_format($sl,0)."</td>
						<td style='border:1px solid black;'>".number_format($thanh_tien,0)." VNĐ</td>
					</tr><br><br> Trân trọng,<br>Cám ơn.";
					Yii::app()->mailer->Host = 'mail.boxanhfoods.vn';
					Yii::app()->mailer->IsSMTP();
					Yii::app()->mailer->IsHTML(true);
					Yii::app()->mailer->CharSet = 'UTF-8';
					Yii::app()->mailer->SMTPAuth=true;
					Yii::app()->mailer->From = 'sales@boxanhfoods.vn';
					Yii::app()->mailer->Port = 25;
					Yii::app()->mailer->Username = 'sales@boxanhfoods.vn';
					Yii::app()->mailer->Password = 'U8f5os%Gy~Xs';
					Yii::app()->mailer->FromName = 'Sales Bo xanh foods';
					Yii::app()->mailer->AddReplyTo('sales@boxanhfoods.vn');
					Yii::app()->mailer->AddAddress($tmp['email']);
					Yii::app()->mailer->Subject = 'Bo xanh foods gửi bạn kết quả giao dịch số #'.$model->order_id;
					Yii::app()->mailer->Body =  $str;
					Yii::app()->mailer->Send();
				}
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		// $this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		// if(!isset($_GET['ajax']))
			// $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $criteria =new CDbCriteria(array(                    
								'condition' => 'status = 0',
                                'order'=>'creation_datetime desc',

        ));
		$dataProvider=new CActiveDataProvider('Order',
            array(
            'criteria'=>$criteria,
            )
        );
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Order('search');
		$model->unsetAttributes();  // clear any default values
        
		if(isset($_GET['Order']))
			$model->attributes=$_GET['Order'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Order the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Order::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Order $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='dnd-boxanhfood-order-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
